package com.itjob.scott.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.itjob.scott.entity.ChatEntity;
import com.itjob.scott.entity.UserEntity;

/**
 * 定时刷新聊天记录   负责取
 * @author 腾田田
 * com.itjob.scott.servlet.ChatRefreshServlet.java
 * 2016-4-12
 */
public class ChatRefreshServlet extends HttpServlet {
	
	private static final long serialVersionUID = 68046350484587081L;
	
	private static final Gson gson = new Gson();
	
	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//以前的聊天记录
		List<ChatEntity> historys = (List<ChatEntity>) this.getServletContext().getAttribute("chats");
		
		//当前要出现的聊天记录  
		List<ChatEntity> shows = new ArrayList<ChatEntity>();
		
		UserEntity user = (UserEntity) request.getSession().getAttribute("user");
		
		Date lastLoginTime = user.getLastLoginTime();
		
		//去掉登录之前的聊天记录
		for (ChatEntity c : historys) {
			//大于登录时间后的聊天记录都显示出来
			if(c.getSendTime().getTime()>lastLoginTime.getTime()){
				shows.add(c);
			}
		}
		
		
		//把shows转成JSON类型的字符串
		String jieguo= gson.toJson(shows);
		
		//发送到前台
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(jieguo);
		out.flush();
		out.close();
		
	}

}
